var tablename = "friends";
var $ = require("../../include/$");
module.exports = {
	get: function(req, res) {
		var finner = req.models[tablename].find({
			myid: req.query.myid
		});
		if (req.cookies.list && (req.cookies.myid == req.query.myid)) {
			res.send(req.cookies.list);
		} else {
			// console.log(req.query);
			finner.run(function(err, result) {
				if (err) {
					res.send(500, err);
				} else
				if (!result.length) {
					res.send(404, "no found!");
				} else {
					var _RES = result;
					console.log(JSON.stringify(result))
					// console.log(req.cookies)
					res.cookie("list", _RES);
					res.cookie("myid", req.query.myid);
					res.send(_RES);
				};
			});
		}
	},
	post: function(req, res) {
		var data = req.body;
		var _old = {};
		_old.myid = data.chat.myid;
		_old.sid = data.chat.sid;
		_old.tid = data.chat.tid;
		var finner = req.models['chat'].find(_old);
		finner.run(function(err, result) {
			if (err) {
				res.send(500, err);
			} else {
				if (!result.length) {

					req.models.chat.create($.extend({}, data.chat), function(err, result) {
						if (err) {
							res.send(500, err);
						} else {
							data.a.chatid = result.chatid;
							data.b.chatid = result.chatid;
							console.log(result.chatid);
							req.models.friends.create([data.a, data.b], function(err, result) {
								if (err) {
									res.send(500, err);
								} else {
									res.send(result);
									res.end();
								};
							})
						};
					})
				} else {
					res.send({
						already: true,
						text: "你们已经是好友啦，不用重复添加哦！！！"
					});
				};
			};
		})
	}
}